/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import hibernate.Request;
import hibernate.RequestStatus;
import hibernate.User;
import hibernate.UserDAO;
import hibernate.UserRole;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.NamingException;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.apache.velocity.*;
import org.apache.velocity.app.Velocity;
/**
 *
 * @author aboyko
 */
@Stateless
@LocalBean
public class MessageManager extends ManagedEJB {

    private Security security;
    @EJB
    private UserDAO UserDAO;

    /*
     * Отправка письма
     */
    public void sendMail(InternetAddress email[], String subject, String body) throws NamingException, MessagingException, IOException {
            Properties props = new Properties();
            props.load(getClass().getResourceAsStream("mail.properties"));
            Session session = Session.getDefaultInstance(props);
            session.setDebug(true);
            Transport transport = session.getTransport();
            transport.connect(props.getProperty("host"),
                              Integer.parseInt(props.getProperty("port")),
                              props.getProperty("user"),
                              props.getProperty("password"));
            
            MimeMessage message = new MimeMessage(session);
            message.setSubject(subject);
            message.setContent(body, "text/html; charset=UTF-8");
            message.addRecipients(Message.RecipientType.TO, email);
            message.setSentDate(new Date());
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    }

    /*
     * Подготовка адресов для отправки,
     * если статус заявки "In progress" делаем рассылку менеджерам,
     * иначе отсылаем письмо пользователю
     */
    public void sendMailSwitch(Request r) throws MessagingException, NamingException, IOException {

            InternetAddress[] emails = null;
            String subject = null;
            String contex;

            if (r.getStatus().equals(RequestStatus.GET_IN_PROGRESS_STATUS())) {
                List<User> manager = security.getUsersByRole(UserRole.GET_MANAGER_ROLE());
                subject = "New request";
                if (!(manager == null || manager.isEmpty())) {
                    emails = new InternetAddress[manager.size()];
                    for (int i = 0; i < manager.size(); i++) {
                        try {
                            emails[i] = (new InternetAddress(manager.get(i).getEmail()));
                        } catch (AddressException ex) {
                            Logger.getLogger(MessageManager.class.getName()).log(Level.SEVERE, null, ex);
                        }                  
                    }
                }
            } else {
                try {
                    emails = new InternetAddress[1];
                    emails[0] = new InternetAddress(r.getUser().getEmail());
                    subject = "Request #" + Long.toString(r.getId());
                } catch (AddressException ex) {
                    Logger.getLogger(MessageManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            contex = getContex(r);
            sendMail(emails, subject, contex);

    }

    /*
     * Подготовка содержимого для отправки
     */
    public String getContex(Request r) {
        try {

            Properties props = new Properties();
            props.load(getClass().getResourceAsStream("velocity.properties"));
            Velocity.init(props);
         
            VelocityContext vc = new VelocityContext();
            vc.put("request", r.getId());
            vc.put("user", r.getUser().getFirstName() + " " + r.getUser().getLastName());
            vc.put("description", r.getDescription());
            vc.put("status", r.getStatus().getDescription());
            vc.put("goods", r.getProduct().getDescription());
           
            if (r.getStatus().equals(RequestStatus.GET_IN_PROGRESS_STATUS())) {
                vc.put("stcolor", "#4682B4");
                vc.put("manager", "");
            } else if (r.getStatus().equals(RequestStatus.GET_REJECTED_STATUS())) {
                vc.put("stcolor", "#FF0000");
                vc.put("manager", r.getManager().getFirstName() + " " + r.getManager().getLastName());
            } else {
                vc.put("stcolor", "#32CD32");
                vc.put("manager", r.getManager().getFirstName() + " " + r.getManager().getLastName());
            }
      
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
	    vc.put("date", dateFormat.format(r.getInDate()));
            
            Template template = Velocity.getTemplate("mailRequest.vm");
            StringWriter sw = new StringWriter();
            template.merge(vc, sw);
            sw.flush();
            sw.close();
            return sw.toString();
        } catch (IOException ex) {
            Logger.getLogger(MessageManager.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    public boolean init(ServerManager serverManager) {
        //Оставить этот код без изменений!
        if (!super.init(serverManager)) {
            return false;
        }
        //Подключать необходимые бины ниже.
        security = serverManager.getSecurity();
        return true;
    }
}
